<template>
  <div class="pagination">
    <el-pagination
      v-show="total > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[10, 20, 30, 50, 100]"
      :pager-count="pagerCount"
      :total="total"
      class="float-right mb-15px mt-15px"
      layout="total, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script lang="ts" setup>
import { computed } from 'vue'

defineOptions({ name: 'Pagination' })

const props = defineProps({
  // 总条目数
  total: {
    required: true,
    type: Number
  },

  // 当前页数：pageNo
  page: {
    type: Number,
    default: 1
  },

  // 每页显示条目个数：pageSize
  limit: {
    type: Number,
    default: 20
  },

  // 设置最大页码按钮数。 页码按钮的数量，当总页数超过该值时会折叠
  pagerCount: {
    type: Number,
    default: 7
  }
})

const emit = defineEmits(['update:page', 'update:limit', 'pagination'])

/**
 * 当前页码
 */
const currentPage = computed({
  get() {
    return props.page
  },

  set(val) {
    emit('update:page', val)
  }
})

/**
 * 每页显示数量
 */
const pageSize = computed({
  get() {
    return props.limit
  },

  set(val) {
    emit('update:limit', val)
  }
})

/**
 * 分页组件每页显示数量改变事件
 * @param val 每页显示数量
 */
const handleSizeChange = val => {
  // 如果修改后超过最大页面，强制跳转到第 1 页
  if (currentPage.value * val > props.total) {
    currentPage.value = 1
  }

  emit('pagination', { page: currentPage.value, limit: val })
}

/**
 * 分页组件页码改变事件
 * @param val 当前页码
 */
const handleCurrentChange = val => {
  emit('pagination', { page: val, limit: pageSize.value })
}
</script>

<style lang="scss" scoped>
@use '@/style/mixins' as *;

.pagination {
  $bgColor: #f8f8f8;
  @include size(100%, 32px);
  @include flex();
  flex-direction: column;
}
</style>
